package com.qingcheng.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qingcheng.dao.OrderConfigMapper;
import com.qingcheng.dao.OrderItemMapper;
import com.qingcheng.dao.OrderLogMapper;
import com.qingcheng.dao.OrderMapper;
import com.qingcheng.entity.PageResult;
import com.qingcheng.pojo.order.*;
import com.qingcheng.service.goods.SkuService;
import com.qingcheng.service.order.CartService;
import com.qingcheng.service.order.OrderService;
import com.qingcheng.util.IdWorker;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Service(interfaceClass = OrderService.class)
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 返回全部记录
     *
     * @return
     */
    public List<Order> findAll() {
        return orderMapper.selectAll();
    }

    /**
     * 分页查询
     *
     * @param page 页码
     * @param size 每页记录数
     * @return 分页结果
     */
    public PageResult<Order> findPage(int page, int size) {
        PageHelper.startPage(page, size);
        Page<Order> orders = (Page<Order>) orderMapper.selectAll();
        return new PageResult<Order>(orders.getTotal(), orders.getResult());
    }

    /**
     * 条件查询
     *
     * @param searchMap 查询条件
     * @return
     */
    public List<Order> findList(Map<String, Object> searchMap) {
        Example example = createExample(searchMap);
        return orderMapper.selectByExample(example);
    }

    /**
     * 分页+条件查询
     *
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    public PageResult<Order> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page, size);
        Example example = createExample(searchMap);
        Page<Order> orders = (Page<Order>) orderMapper.selectByExample(example);
        return new PageResult<Order>(orders.getTotal(), orders.getResult());
    }

    /**
     * 根据Id查询
     *
     * @param id
     * @return
     */
    public Order findById(String id) {
        return orderMapper.selectByPrimaryKey(id);
    }


    @Autowired
    private CartService cartService;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Reference
    private SkuService skuService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 新增
     *
     * @param order
     */
    public Map<String, Object> add(Order order) {
        //获取购物车(刷新单价)
        List<Map<String, Object>> oderItemList = cartService.findNewOrderItemList(order.getUsername());
        //获取选中的购物车
        List<OrderItem> orderItems = oderItemList.stream()
                .filter(cart -> (boolean) cart.get("checked"))
                .map(cart -> (OrderItem) cart.get("item"))
                .collect(Collectors.toList());
        //扣减库存
        if (!skuService.deductionStock(orderItems)) {
            throw new RuntimeException("库存扣减失败");
        }

        try {
            //保存订单主表
            order.setId(idWorker.nextId() + "");
            //合计数计算
            IntStream numStream = orderItems.stream().mapToInt(OrderItem::getNum);
            IntStream moneyStream = orderItems.stream().mapToInt(OrderItem::getMoney);
            int totalNum = numStream.sum();//总数量
            int totalMoney = moneyStream.sum();//订单总金额
            int preMoney = cartService.preferential(order.getUsername()); // 计算优惠金额
            order.setTotalNum(totalNum);//总数量
            order.setTotalMoney(totalMoney);//总金额
            order.setPreMoney(preMoney);//优惠金额
            order.setPayMoney(totalMoney - preMoney);//支付金额=总金额+优惠金额
            order.setCreateTime(new Date());//订单创建日期
            order.setOrderStatus("0"); // 订单状态
            order.setPayStatus("0"); // 支付状态：未支付
            order.setConsignStatus("0"); //发货状态：未发货
            orderMapper.insert(order);

            double proportion = (double) order.getPayMoney() / totalMoney;
            //保存订单明细
            for (OrderItem orderItem : orderItems) {
                orderItem.setOrderId(order.getId());//订单主表ID
                orderItem.setId(idWorker.nextId() + "");
                orderItem.setPayMoney((int) (orderItem.getMoney() * proportion));//支付金额
                orderItemMapper.insert(orderItem);
            }
        } catch (Exception e) {
            rabbitTemplate.convertAndSend("","queue.skuback", JSON.toJSONString(orderItems));
            throw new RuntimeException("订单生成失败"); //抛出异常，让其回滚！
        }
        //清除选中的购物车
        cartService.deleteCheckedCart(order.getUsername());
        //返回订单号和支付的金额
        Map<String, Object> map = new HashMap();
        map.put("ordersn", order.getId());
        map.put("money", order.getPayMoney());
        return map;
    }

    /**
     * 修改
     *
     * @param order
     */
    public void update(Order order) {
        orderMapper.updateByPrimaryKeySelective(order);
    }

    /**
     * 删除
     *
     * @param id
     */
    public void delete(String id) {
        orderMapper.deleteByPrimaryKey(id);
    }


    /**
     * 返回订单详情与订单明细
     *
     * @param id
     * @return
     */
    @Override
    public OrderAndOrderItem findOrderResultById(String id) {
        //得到订单详情
        Order order = orderMapper.selectByPrimaryKey(id);
        //创建条件对象
        Example example = new Example(OrderItem.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderId", id);
        //返回orderitem结果集
        List<OrderItem> orderItems = orderItemMapper.selectByExample(example);
        //创建返回值对象
        OrderAndOrderItem orderAndOrderItem = new OrderAndOrderItem();
        orderAndOrderItem.setOrder(order);
        orderAndOrderItem.setOrderItemList(orderItems);
        return orderAndOrderItem;
    }

    /**
     * 根据订单ID数据查询订单集合
     *
     * @param searchMap
     * @return
     */
    @Override
    public List<Order> findOrderListByIds(Map searchMap) {
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        //将json对象中的ids转成集合
        List idsList = new ArrayList<>();
        if (!"".equals(searchMap.get("ids")) && searchMap.get("ids") != null) {
            JSONArray ids = (JSONArray) searchMap.get("ids");
            for (Object id : ids) {
                idsList.add(id);
            }
            //条件一 id属于id集合
            criteria.andIn("id", idsList);
            //条件儿 发货状态为未发货0
            criteria.andEqualTo("consignStatus", searchMap.get("consignStatus"));
        }

        //根据条件对象查询结果集
        List<Order> orders = orderMapper.selectByExample(example);
        return orders;
    }

    /**
     * 批量修改订单状态、发货状态、发货时间。
     *
     * @param orders
     */
    @Override
    public void batchSend(List<Order> orders) {
        //判断单号和物流公司是否为空
        for (Order order : orders) {
            if (order.getShippingCode() == null || order.getShippingName() == null) {
                throw new RuntimeException("请选择物流公司或填写单号");
            }
        }

        //遍历订单更新表
        for (Order order : orders) {
            order.setOrderStatus("1");//设置订单状态
            order.setConsignStatus("1");//设置发货状态
            order.setConsignTime(new Date());//设置发货时间
            orderMapper.updateByPrimaryKeySelective(order);//更新order表
        }
    }

    @Autowired
    private OrderConfigMapper orderConfigMapper;

    @Autowired
    private OrderLogMapper orderLogMapper;

    /**
     * 订单超时处理
     */
    @Override
    public void orderTimeOutLogic() {
        //订单超时未付款 自动关闭
        //查询超时时间
        OrderConfig orderConfig = orderConfigMapper.selectByPrimaryKey(1);
        Integer orderTimeout = orderConfig.getOrderTimeout();//超时时间
        LocalDateTime localDateTime = LocalDateTime.now().minusMinutes(orderTimeout);//得到超时的时间点 获得前一小时

        //设置查询条件
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andLessThan("createTime", localDateTime);//创建时间小于超时时间
        criteria.andEqualTo("orderStatus", "0");//未付款的
        criteria.andEqualTo("idDelete", "0");//未删除的

        //查询超时订单
        List<Order> orders = orderMapper.selectByExample(example);
        for (Order order : orders) {
            //记录订单变动日志
            OrderLog orderLog = new OrderLog();
            orderLog.setOperater("system");//系统
            orderLog.setOperateTime(new Date());//当前日期
            orderLog.setOrderStatus("4");
            orderLog.setPayStatus(order.getPayStatus());
            orderLog.setConsignStatus(order.getConsignStatus());
            orderLog.setRemarks("超时订单，系统自动关闭");
            orderLog.setOrderId(Long.parseLong(order.getId()));
            orderLogMapper.insert(orderLog);
            //更改订单状态
            order.setOrderStatus("4");
            order.setCloseTime(new Date());//关闭日期
            orderMapper.updateByPrimaryKeySelective(order);
        }

    }


    /**
     * @param orderItems 订单明细拆分对象
     * @return
     */
    @Override
    public void splitOrderItem(List<OrderItem> orderItems) {
        //新订单明细集合
        List<OrderItem> newOrderItems = new ArrayList<>();
        //记录主订单详情Id
        String orderId = "";
        for (OrderItem orderItem : orderItems) {
            //1.获得订单明细
            OrderItem orderItem1 = orderItemMapper.selectByPrimaryKey(orderItem.getId());
            orderId = orderItem1.getOrderId();
            //2.新订单明细对象
            OrderItem orderItemNew = new OrderItem();
            //3.对象属性复制
            BeanUtils.copyProperties(orderItem1, orderItemNew);
            //4.修改主订单明细数量和金额
            orderItem1.setNum(orderItem1.getNum() - orderItem.getNum());
            //5.修改主订单明细总金额
            orderItem1.setMoney(orderItem1.getNum() * orderItem1.getPrice());
            //6.修改主订单明细实付金额
            orderItem1.setPayMoney(orderItem1.getNum() * orderItem1.getPrice() + orderItem1.getPostFee());
            orderItemMapper.updateByPrimaryKeySelective(orderItem1);//更新主表数据库
            //7.修改从订单明细数据
            orderItemNew.setNum(orderItem.getNum());//设置拆分数量
            orderItemNew.setMoney(orderItemNew.getNum() * orderItemNew.getPrice());//修改从订单明细总金额
            orderItemNew.setPayMoney(orderItemNew.getNum() * orderItemNew.getPrice() + orderItemNew.getPostFee());//修改从订单明细实付金额
            newOrderItems.add(orderItemNew);
        }

        //处理订单详情功能
        //1.获得订单详情+明细
        OrderAndOrderItem orderResultOld = findOrderResultById(orderId);
        //2.复制订单详情对象
        Order newOrder = new Order();
        BeanUtils.copyProperties(orderResultOld.getOrder(), newOrder);
        //3.修改主订单详情数据
        int orderNum = 0;
        int orderMoney = 0;
        for (OrderItem orderItem : orderResultOld.getOrderItemList()) {
            orderNum += orderItem.getNum(); //记录总数量
            orderMoney += orderItem.getPayMoney();//记录总付款金额
        }
        orderResultOld.getOrder().setTotalNum(orderNum);//更新主订单详情总数量
        orderResultOld.getOrder().setPayMoney(orderMoney);
        orderMapper.updateByPrimaryKeySelective(orderResultOld.getOrder());//更新主订单数据
        //4.修改从订单详情数据
        int newOrderNum = 0;
        int newOrderMoney = 0;
        newOrder.setId(idWorker.nextId() + "");
        for (OrderItem orderItem : newOrderItems) {
            //修改从订单明细Id
            orderItem.setId(idWorker.nextId() + "");
            newOrderNum += orderItem.getNum(); //记录总数量
            newOrderMoney += orderItem.getPayMoney();//记录总付款金额
            orderItem.setOrderId(newOrder.getId()); //设置从订单详情关联
        }
        newOrder.setTotalNum(newOrderNum); //更新从订单详情总数量
        newOrder.setPayMoney(newOrderMoney);
        orderMapper.insert(newOrder);//新增从订单详情
        //新增从订单明细
        for (OrderItem orderItem : newOrderItems) {
            orderItemMapper.insert(orderItem);// 插入从订单
        }
    }

    /**
     * 合并订单
     *
     * @param orderId1
     * @param orderId2
     */
    @Override
    public void merge(String orderId1, String orderId2) {
        System.out.println(orderId1);
        System.out.println(orderId2);
        Order order1 = orderMapper.selectByPrimaryKey(orderId1);//主订单
        Order order2 = orderMapper.selectByPrimaryKey(orderId2);//从订单

        //判断订单是否被删除,若被删除则提示用户订单不存在
        if ("1".equals(order1.getIsDelete())) {
            throw new RuntimeException("编号为:" + orderId1 + "不存在");
        }
        if ("1".equals(order2.getIsDelete())) {
            throw new RuntimeException("编号为:" + orderId2 + "不存在");
        }

        Example example1 = new Example(OrderItem.class);
        Example.Criteria criteria1 = example1.createCriteria();
        criteria1.andEqualTo("orderId", orderId1);
        List<OrderItem> orderItems1 = orderItemMapper.selectByExample(example1);//主订单明细

        Example example2 = new Example(OrderItem.class);
        Example.Criteria criteria2 = example2.createCriteria();
        criteria2.andEqualTo("orderId", orderId2);
        List<OrderItem> orderItems2 = orderItemMapper.selectByExample(example2);//.从订单明细

        //存放合并后的订单明细
        Map<String, OrderItem> map = new HashMap<>();
        Map map1 = addOrderItem(map, orderItems1);
        Map map2 = addOrderItem(map1, orderItems2);
        for (Object value : map2.values()) {
            OrderItem orderItem = (OrderItem) value;
            orderItemMapper.updateByPrimaryKeySelective(orderItem);
        }
//        for (OrderItem orderItem : orderItems1) {
//            if(map.containsKey(orderItem.getSkuId())){//假如是同一个商品
//                OrderItem orderItem1 = map.get(orderItem.getSkuId());//获取已存在的商品信息
//                orderItem1.setNum(orderItem1.getNum() + orderItem.getNum());//数量相加
//                orderItem1.setMoney(orderItem1.getMoney() + orderItem.getMoney());//总金额相加
//                orderItem1.setPayMoney(orderItem1.getPayMoney() + orderItem.getPayMoney());//实付金额相加
//                orderItem1.setPostFee(orderItem1.getPostFee() + orderItem.getPostFee());//运费相加
//            }
//        }
//
//        for (OrderItem orderItem : orderItems2) {
//            if(map.containsKey(orderItem.getSkuId())){//假如是同一个商品
//                OrderItem orderItem2 = map.get(orderItem.getSkuId());//获取已存在的商品信息
//                orderItem2.setNum(orderItem2.getNum() + orderItem.getNum());//数量相加
//                orderItem2.setMoney(orderItem2.getMoney() + orderItem.getMoney());//总金额相加
//                orderItem2.setPayMoney(orderItem2.getPayMoney() + orderItem.getPayMoney());//实付金额相加
//                orderItem2.setPostFee(orderItem2.getPostFee() + orderItem.getPostFee());//运费相加
//            }
//        }

//        //循环遍历主订单明细表
//        for (OrderItem value : map2.values()) {
//            orderItemMapper.updateByPrimaryKeySelective(value);
//        }

        order1.setTotalNum(order1.getTotalNum() + order2.getTotalNum());//合并合计数量
        order1.setTotalMoney(order1.getTotalMoney() + order2.getTotalMoney());//合并合计金额
        order1.setPreMoney(order1.getPreMoney() + order2.getPreMoney());//合并优惠金额
        order1.setPostFee(order1.getPostFee() + order2.getPostFee());//合并邮费
        order1.setPayMoney(order1.getPayMoney() + order2.getPayMoney());//合并实付金额
        order2.setIsDelete("1");//伪删除从订单
        orderMapper.updateByPrimaryKeySelective(order1);//更新主订单信息
        orderMapper.updateByPrimaryKeySelective(order2);//更新从订单信息
    }

    @Override
    @Transactional
    public void updatePayStatus(String orderId, String transactionId) {
        System.out.println("调用修改订单状态");
        Order order = orderMapper.selectByPrimaryKey(orderId);
        if(order!=null && "0".equals( order.getPayStatus() )){
            //修改订单状态等信息
            order.setPayStatus("1");//支付状态
            order.setOrderStatus("1");//订单状态
            order.setUpdateTime(new Date());//修改日期
            order.setPayTime(new Date());//支付日期
            order.setTransactionId(transactionId);//交易流水号
            orderMapper.updateByPrimaryKeySelective(order);//修改

            //记录订单日志
            OrderLog orderLog=new OrderLog();
            orderLog.setId( idWorker.nextId()+"" );
            orderLog.setOperater("system");//系统
            orderLog.setOperateTime(new Date());//操作时间
            orderLog.setOrderStatus("1");//订单状态
            orderLog.setPayStatus("1");//支付状态
            orderLog.setRemarks("支付流水号："+transactionId);//备注
            orderLog.setOrderId(Long.valueOf(orderId));
            orderLogMapper.insert(orderLog);

        }


    }

    private <K, T, V> Map<K, V> addOrderItem(Map<K, V> map, List<T> list) {
        for (T t : list) {
            OrderItem orderItem = (OrderItem) t;
            if (map.containsKey(orderItem.getSkuId())) {//假如是同一个商品
                OrderItem orderItem1 = (OrderItem) map.get(orderItem.getSkuId());//获取已存在的商品信息
                orderItem1.setNum(orderItem1.getNum() + orderItem.getNum());//数量相加
                orderItem1.setMoney(orderItem1.getMoney() + orderItem.getMoney());//总金额相加
                orderItem1.setPayMoney(orderItem1.getPayMoney() + orderItem.getPayMoney());//实付金额相加
                orderItem1.setPostFee(orderItem1.getPostFee() + orderItem.getPostFee());//运费相加
            }
        }
        return map;
    }


    /**
     * 构建查询条件
     *
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap) {
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        if (searchMap != null) {
            // 订单id
            if (searchMap.get("id") != null && !"".equals(searchMap.get("id"))) {
                criteria.andLike("id", "%" + searchMap.get("id") + "%");
            }
            // 支付类型，1、在线支付、0 货到付款
            if (searchMap.get("payType") != null && !"".equals(searchMap.get("payType"))) {
                criteria.andLike("payType", "%" + searchMap.get("payType") + "%");
            }
            // 物流名称
            if (searchMap.get("shippingName") != null && !"".equals(searchMap.get("shippingName"))) {
                criteria.andLike("shippingName", "%" + searchMap.get("shippingName") + "%");
            }
            // 物流单号
            if (searchMap.get("shippingCode") != null && !"".equals(searchMap.get("shippingCode"))) {
                criteria.andLike("shippingCode", "%" + searchMap.get("shippingCode") + "%");
            }
            // 用户名称
            if (searchMap.get("username") != null && !"".equals(searchMap.get("username"))) {
                criteria.andLike("username", "%" + searchMap.get("username") + "%");
            }
            // 买家留言
            if (searchMap.get("buyerMessage") != null && !"".equals(searchMap.get("buyerMessage"))) {
                criteria.andLike("buyerMessage", "%" + searchMap.get("buyerMessage") + "%");
            }
            // 是否评价
            if (searchMap.get("buyerRate") != null && !"".equals(searchMap.get("buyerRate"))) {
                criteria.andLike("buyerRate", "%" + searchMap.get("buyerRate") + "%");
            }
            // 收货人
            if (searchMap.get("receiverContact") != null && !"".equals(searchMap.get("receiverContact"))) {
                criteria.andLike("receiverContact", "%" + searchMap.get("receiverContact") + "%");
            }
            // 收货人手机
            if (searchMap.get("receiverMobile") != null && !"".equals(searchMap.get("receiverMobile"))) {
                criteria.andLike("receiverMobile", "%" + searchMap.get("receiverMobile") + "%");
            }
            // 收货人地址
            if (searchMap.get("receiverAddress") != null && !"".equals(searchMap.get("receiverAddress"))) {
                criteria.andLike("receiverAddress", "%" + searchMap.get("receiverAddress") + "%");
            }
            // 订单来源：1:web，2：app，3：微信公众号，4：微信小程序  5 H5手机页面
            if (searchMap.get("sourceType") != null && !"".equals(searchMap.get("sourceType"))) {
                criteria.andLike("sourceType", "%" + searchMap.get("sourceType") + "%");
            }
            // 交易流水号
            if (searchMap.get("transactionId") != null && !"".equals(searchMap.get("transactionId"))) {
                criteria.andLike("transactionId", "%" + searchMap.get("transactionId") + "%");
            }
            // 订单状态
            if (searchMap.get("orderStatus") != null && !"".equals(searchMap.get("orderStatus"))) {
                criteria.andLike("orderStatus", "%" + searchMap.get("orderStatus") + "%");
            }
            // 支付状态
            if (searchMap.get("payStatus") != null && !"".equals(searchMap.get("payStatus"))) {
                criteria.andLike("payStatus", "%" + searchMap.get("payStatus") + "%");
            }
            // 发货状态
            if (searchMap.get("consignStatus") != null && !"".equals(searchMap.get("consignStatus"))) {
                criteria.andLike("consignStatus", "%" + searchMap.get("consignStatus") + "%");
            }
            // 是否删除
            if (searchMap.get("isDelete") != null && !"".equals(searchMap.get("isDelete"))) {
                criteria.andLike("isDelete", "%" + searchMap.get("isDelete") + "%");
            }

            // 数量合计
            if (searchMap.get("totalNum") != null) {
                criteria.andEqualTo("totalNum", searchMap.get("totalNum"));
            }
            // 金额合计
            if (searchMap.get("totalMoney") != null) {
                criteria.andEqualTo("totalMoney", searchMap.get("totalMoney"));
            }
            // 优惠金额
            if (searchMap.get("preMoney") != null) {
                criteria.andEqualTo("preMoney", searchMap.get("preMoney"));
            }
            // 邮费
            if (searchMap.get("postFee") != null) {
                criteria.andEqualTo("postFee", searchMap.get("postFee"));
            }
            // 实付金额
            if (searchMap.get("payMoney") != null) {
                criteria.andEqualTo("payMoney", searchMap.get("payMoney"));
            }

        }
        return example;
    }

}
